package pl.mmirski.functests.selenium;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Nullable;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.google.common.base.Function;

public class SeleniumBase {

	protected static WebDriver driver;
	private static StringBuffer verificationErrors = new StringBuffer();

	@BeforeClass
	public static void setUp() throws Exception {
		driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@AfterClass
	public static void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	public SeleniumBase() {
		super();
	}

	protected void clickOnElement(By by) {
		driver.findElement(by).click();
	
	}

	protected void goToURL(String URL) {
		driver.get(URL);
	}

	protected void assertAgileByExamplePageIsOpened() {
		assertTextIsPresent(By.cssSelector("h1.ir"), 
				"AgileByExample conference");				
	}
	
	protected void assertTextIsPresent(By by, String text) {
		assertEquals(text,
				driver.findElement(by).getText());		
	}

	protected boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}	
	
	protected void inputText(By by, String text) {
		driver.findElement(by).sendKeys(text);
	}
	
	protected void waitForElement(final By by) {
		WebDriverWait wait = new WebDriverWait(driver, 30);
		
		wait.until(new Function<WebDriver,WebElement>() {

			@Override
			public WebElement apply(@Nullable WebDriver d) {
				return d.findElement(by);
			} 
			 
		});
		
	}
	
	protected void waitForElementOnTheList(final By by, final String text) {
		WebDriverWait wait = new WebDriverWait(driver, 30);
		
		wait.until(new Function<WebDriver,WebElement>() {

			@Override
			public WebElement apply(@Nullable WebDriver d) {
				List<WebElement> elementList = d.findElements(by);
				
				WebElement elementPresent = null;
				
				for (int i = 0; i < elementList.size(); i++) {
					WebElement we = elementList.get(i);
					if (we.getText().contains(text)) {
						elementPresent = we;
					}
				}
				return elementPresent;				
				
			} 
			 
		});
		
	}
	

}